<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import LayoutRightContainer from '@/views/layout-right-container.vue'
import {
    fetchBannerModes, createBanner, fetchBannerBasic,
    fetchBannerRemove
} from '@/api/banner.services.js'
import {
    Plus, Delete, Edit, SuccessFilled,
    CircleCloseFilled
} from '@element-plus/icons-vue'
const breadcrumb = ref([
    { label: '系统管理' },
    { label: 'banner管理' }
])
const searchForm = ref({
    total: 0,
    page: 1,
    limit: 20
})
const addForm = ref({
    status: 1,
    bannerImage: null // 存储图片的base64数据
})
const formRules = reactive({
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    mode: [{ required: true, message: '请选择所属模块', trigger: 'change' }],
    image: [{ required: true, message: '请上传banner图片', trigger: 'change' }]
})

// 添加tableData和loading的定义
const tableData = ref([])
const loading = ref(false)

const submit = async () => {
    // 检查addFormRef是否存在
    if (!addFormRef.value) {
        ElMessage.error('表单初始化失败，请重试')
        return
    }
    const valid = await addFormRef.value.validate()
    if (!valid) return
    const uploadLoading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    const result = await createBanner(addForm.value)
    if (result.code == 1) {
        show.value = false
        uploadLoading.close()
        ElMessage.success(addForm.id ? '编辑成功' : '添加成功')
        initTableData()
    }
}

const addFormRef = ref(null)
const beforeUpload = (file) => {
    // 使用FileReader将图片转换为base64格式
    const reader = new FileReader()
    reader.onload = (e) => {
        addForm.value.image = reader.result // 将base64数据存储到表单中
    }
    reader.readAsDataURL(file.raw)
}
const modes = ref([])
const fetchModesData = async () => {
    const result = await fetchBannerModes()
    if (result.code === 1) {
        modes.value = result.data
    }
}

const initTableData = async () => {
    loading.value = true
    const result = await fetchBannerBasic(searchForm.value)
    if (result.code == 1) {
        loading.value = false
        searchForm.total = result.data.total
        tableData.value = result.data.data
    }
}
initTableData()
fetchModesData()
const handleCurrentChange = (page) => {
    searchForm.value.page = page
    initTableData()
}

const handleSizeChange = (limit) => {
    searchForm.value.limit = limit
    searchForm.value.page = 1
    initTableData()
}
const remove = async (ids) => {
    try {
        await ElMessageBox.confirm('确定删除所选banner图吗？')
        const result = await fetchBannerRemove({ id: ids })
        if (result.code == 1) {
            initTableData()
            ElMessage.success('删除成功')
        }

    } catch (error) {
        console.log(error)
    }
}

</script>
<template>
    <LayoutRightContainer :breadcrumb="breadcrumb">
        <div :class="$style['main-container']">
            <div :class="$style['search-container']">
                <el-form :model="searchForm" :class="$style['form-warpper']" inline>
                    <el-form-item>
                        <el-input v-model="searchForm.title" placeholder="请输入标题" clearable />
                    </el-form-item>
                    <el-form-item>
                        <el-select v-model="searchForm.mode" placeholder="所属模块" clearable>
                            <el-option v-for="(item, index) in modes" :key="index" :label="item" :value="item" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="initTableData">查询</el-button>
                    </el-form-item>
                </el-form>
                <el-button type="primary" :icon="Plus" @click="addForm = {}; show = true">添加</el-button>
            </div>
            <el-table :data="tableData" ref="refTable" row-key="id" :class="$style['table-wrapper']"
                v-loading="loading">
                <el-table-column label="标题" prop="title" align="center" />
                <el-table-column label="banner图片" align="center">
                    <template #default="{ row }">
                        <el-image v-if="row.image" :src="row.image" :class="$style['images-wrapper']"
                            :preview-src-list="[row.image]" fit="cover" preview-teleported />
                    </template>
                </el-table-column>
                <el-table-column label="所属模块" prop="mode_name" align="center" />
                <el-table-column label="跳转链接" prop="url" align="center" />
                <el-table-column label="启用状态" prop="disable" align="center">
                    <template #default="{ row }">
                        <el-icon v-if="row.disable == 1" color="#40bf40">
                            <SuccessFilled />
                        </el-icon>
                        <el-icon v-else color="#cccccc">
                            <CircleCloseFilled />
                        </el-icon>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="{ row }">
                        <div :class="$style['tools-wrapper']">
                            <el-link type="primary" :icon="Edit" @click="addForm = row; show = true"
                                :underline="false">编辑</el-link>
                            <el-link type="danger" :icon="Delete" :underline="false"
                                @click="remove([row.id])">删除</el-link>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div :class="$style['flex-end']">
                <el-pagination v-model:current-page="searchForm.page" v-model:page-size="searchForm.limit" size="small"
                    background layout="sizes,total,prev, pager, next" :total="searchForm.total"
                    :hide-on-single-page="false" :page-sizes="[20, 50, 100, 200]" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </div>
    </LayoutRightContainer>

    <el-drawer v-model="show" :title="addForm.id ? '编辑' : '添加'" :size="600" :close-on-click-modal="false"
        :close-on-press-escape="false" :class="$style['drawer-container']">
        <el-form ref="addFormRef" :model="addForm" :rules="formRules" label-width="100px">
            <el-form-item label="banner标题" prop="title">
                <el-input v-model="addForm.title" placeholder="请输入banner标题" />
            </el-form-item>
            <el-form-item label="所属模块" prop="mode">
                <el-select v-model="addForm.mode" placeholder="请选择模块" clearable>
                    <el-option v-for="(item, index) in modes" :key="index" :label="item" :value="index" />
                </el-select>
            </el-form-item>
            <el-form-item label="跳转链接" prop="url">
                <el-input v-model="addForm.url" placeholder="请输入跳转链接" />
            </el-form-item>
            <el-form-item label="启用状态" prop="disable">
                <el-radio-group v-model="addForm.disable">
                    <el-radio :value="1">启用</el-radio>
                    <el-radio :value="2">禁用</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="banner图" prop="image">
                <el-upload :class="$style['image-uploader']" :show-file-list="false" :on-change="beforeUpload"
                    :http-request="handleUpload">
                    <img :src="addForm.image" :class="$style['avatar']"
                        v-if="addForm.image && typeof addForm.image === 'string'" />
                    <el-icon :class="$style['avatar-uploader-icon']" v-else>
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="addForm = {}; show = false">取消</el-button>
                <el-button type="primary" @click="submit">提交</el-button>
            </div>
        </template>
    </el-drawer>
</template>
<style lang="scss" module>
.main-container {
    display: flex;
    flex-direction: column;
    height: 100%;
    background: #FFF;
    border-radius: 5px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
    padding: 0 10px;
}

.search-container {
    display: flex;
    flex-direction: row;
    height: 50px;
    align-items: center;
    justify-content: space-between;
}

.form-warpper {

    & [class~='el-form-item'] {
        margin-bottom: 0;
        margin-right: 10px;
    }

    & [class~='el-input'] {
        width: 200px;
    }

    & [class~='el-select'] {
        width: 200px;
    }
}

.table-wrapper {
    flex: 1;

    & [class~='el-table__cell'] {
        z-index: initial;
    }
}

.flex-end {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    height: 35px;
}

.tools-wrapper {
    display: flex;
    flex-direction: row;
    justify-content: center;

    & [class~='el-link'] {
        margin-right: 15px;
    }
}

.background-uploader {
    width: 280px;
    height: 120px;
}

.logo-avatar {
    width: 280px;
    height: 120px;
    display: block;
    border: 1px dashed var(--el-border-color);
}

.avatar {
    width: 280px;
    height: 120px;
    display: block;
    border: 1px dashed var(--el-border-color);
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #ccc;
    width: 280px;
    height: 120px;
    text-align: center;
    border: 1px dashed var(--el-border-color);
}

.drawer-container {
    &[class~='el-form'] {
        & [class~='el-input'] {
            width: 80%;
        }

        & [class~='el-select'] {
            width: 80%;
        }
    }
}

.images-wrapper {
    width: 100px;
    height: 50px;
}
</style>
